package fr.hoteia.appengine.archetype.server.web.controllers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import fr.hoteia.appengine.archetype.server.service.EmailManager;
import fr.hoteia.appengine.archetype.server.web.form.ContactForm;
import fr.hoteia.appengine.archetype.server.web.form.ValueBean;

@Controller
public class ContactController extends AbstractHoteiaController {

	protected final Log logger = LogFactory.getLog(getClass());

    protected EmailManager emailManager;

    @ModelAttribute("countries")
    public List<ValueBean> getCountries(HttpServletRequest request) {
		List<ValueBean> countriesValues = new ArrayList<ValueBean>();
		
		ResourceBundle countriesResourceBundle = ResourceBundle.getBundle("Countries", getRequestUtil().getCurrentLocale(request));
		Set<String> countriesKey = countriesResourceBundle.keySet();
		
		for (Iterator<String> iterator = countriesKey.iterator(); iterator.hasNext();) {
			String countryKey = (String) iterator.next();
			countriesValues.add(new ValueBean(countryKey.replace("countries.", ""), (String)countriesResourceBundle.getObject(countryKey)));
		}
		
		Collections.sort(countriesValues, new Comparator<ValueBean>() {
			@Override
			public int compare(ValueBean o1, ValueBean o2) {
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		
		return countriesValues;
    }
    
    @RequestMapping(value = "/portal/contactForm*", method = RequestMethod.GET)
    public ModelAndView contactFormForm(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		if(logger.isDebugEnabled()){
			logger.debug("contactForm");
		}
		
		ModelAndView modelAndView = new ModelAndView();
		try {
			
			modelAndView = getModelAndView(request, "contactForm", null);
			
			getRequestUtil().handleRequestLanguage(request, response);
			
			model.addAllAttributes(getDefaultModel(request));
			
		} catch (Exception e) {
			logger.error("Error on the contact controller", e);
		}
    	
		ContactForm contactForm = new ContactForm();
		
		String languageCode = getRequestUtil().getCurrentLanguageCode(request);
		if(languageCode.equals("en")){
			contactForm.setCountryCode("US");
		} else if(languageCode.equals("fr")){
			contactForm.setCountryCode("FR");
		} 
		
    	model.addAttribute("contactForm", contactForm);
		
		return super.handleRequestInternal(request, response, modelAndView);
    }

    @RequestMapping(value = "/portal/contact*", method = RequestMethod.GET)
    public String contact() {
    	return "redirect:contactForm";
    }

    @RequestMapping(value = "/portal/contact*", method = RequestMethod.POST)
    public ModelAndView contact(HttpServletRequest request, HttpServletResponse response, @ModelAttribute ContactForm contactForm, Model model) throws Exception {
		if(logger.isDebugEnabled()){
			logger.debug("contact");
		}
		
		ModelAndView modelAndView = new ModelAndView();
		try {
			
			modelAndView = getModelAndView(request, "contact", null);
			
			getRequestUtil().handleRequestLanguage(request, response);
			
			model.addAllAttributes(getDefaultModel(request));
		
			emailManager.sendEmailContact(contactForm);
			
		} catch (Exception e) {
			logger.error("Error on the contact controller", e);
		}
		
		contactForm.setCountryName(getMessageSource().getMessage("countries." + contactForm.getCountryCode(), null, getRequestUtil().getCurrentLocale(request)));
		
		contactForm.setMessage(contactForm.getMessage().replace("\n", "<br/>"));

    	model.addAttribute("contactForm", contactForm);
    	
		model.addAttribute(contactForm);
		
		return super.handleRequestInternal(request, response, modelAndView);
    }
    
	public void setEmailManager(EmailManager emailManager) {
		this.emailManager = emailManager;
	}
    
}